# -*- coding: utf-8 -*- 
# @Time : 2021-07-27 22:47 
# @Author : derek.zhang 
# @File : serializers.py 
# @Software: PyCharm
from rest_framework import serializers

from cabinet.models import Cabinet
from idcs.models import Idc
from idcs.serializers import IdcSerializer


class CabinetSerializer(serializers.Serializer):
    # idc = IdcSerializer()
    # idc = serializers.PrimaryKeyRelatedField(many=False, queryset=Idc.objects.all())
    idc = serializers.SerializerMethodField()  # 只有该字段为只读的情况才能用  和 get_idc 配合使用
    name = serializers.CharField(required=True)

    def get_idc(self, obj):
        return {
            'id' : obj.id,
            'name': obj.name
        }

    # def to_representation(self, instance):
    #     '''
    #     序列化数据流方向   querySet  --> serializer 类 --》 to_representation
    #     '''
    #     idc_obj = instance.idc
    #     ret =  super(CabinetSerializer, self).to_representation(instance)
    #     ret['idc'] = {
    #         'id': idc_obj.id,
    #         'name' : idc_obj.name
    #     }
    #     print(ret)
    #     return ret

    def to_internal_value(self, data):
        '''反序列化 数据流方向 ：web 提交数据 --》 request body Get/POST/ -->to_internal_value --> 上面的序列化field--》caeate '''
        print(data)
        return super(CabinetSerializer, self).to_internal_value(data)

    def create(self, validate_data):
        return Cabinet.objects.create(**validate_data)
